//index.js
var QQMapWX = require('../../libs/qqmap-wx-jssdk.min.js');
var qqmapsdk;
//获取应用实例
// const app = getApp()

Page({
  data: {
    activeAdress: '未知',
    imgUrl: '',
    hidden: false,
    loadStatus: false,
    loadStatus2: false
  },
  onLoad: function (options) {
    var name = options.name;
    var imageUrl = options.imageUrl;
    if (!name || !imageUrl) {
      // 获取缓存
      wx.getStorage({
        key: 'address',
        success: res => {
          this.setData({
            activeAdress: res.data
          })
        }
      })
      // 实例化API核心类
      qqmapsdk = new QQMapWX({
        key: 'ES5BZ-MXTEW-23DR6-OBIRX-BNFZK-RLBAZ'
      });
      // 获取用户地址
      // console.log(wx.canIUse('getLocation'))
      wx.getLocation({
        success: res => {
          qqmapsdk.reverseGeocoder({
            location: {
              latitude: res.latitude,
              longitude: res.longitude
            },
            success: res => {
              wx.setStorage({
                key: 'address', 
                data: res.result.address_component.city
              })
              this.getMetro(res.result.address_component.city);
              this.setData({
                hidden: true,
                activeAdress: res.result.address_component.city
              })
            },
            fail: (res) => {
              console.log(res);
            },
            complete: () => {
              // console.log(res);
            }
          });
        }
      })
    } else {
      this.setData({
        hidden: true,
        activeAdress: name,
        imgUrl: imageUrl
      })
    }
  },
  // 预览图片
  viewImg: function (e) {
    var cur = e.target.dataset.src.replace(/\s/g, "");
    wx.previewImage({
      current: cur,
      urls: [cur]
    })
  },
  //事件处理函数
  bindViewTap: function () {
    wx.redirectTo({
      url: '../location/location'
    })
  },
  // 获取地铁图
  getMetro: function (address) {
    wx.request({
      url: 'https://www.odun.com/smartShoes/web/subway/citys.json', //
      header: {
        'content-type': 'application/json'
      },
      success: res => {
        var arr = res.data.data.list;
        arr.forEach(el => {
          if (el.name === address) {
            this.setData({
              imgUrl: el.imageUrl
            })
          }
        });
      }
    })
  },
  // 图片加载完成
  loadImg: function () {
    this.setData({
      loadStatus: true
    })
  },
  errImg: function () {
    this.setData({
      loadStatus2: true
    })
  }
})
